package com.sptpc.hellospring.service;

import com.sptpc.hellospring.model.Category;
import com.sptpc.hellospring.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    public Category savaCategory(String name){

        return categoryRepository.save(Category.builder().name(name).build());

    }


    public List<Category> findAll(){
        return categoryRepository.findAll(Sort.by(Sort.Direction.DESC,"createTime"));//凡是hibernate涉及到的属性都是实体类的属性，而不是数据库里面的。
    }


//    public Category findOne(String name) {
//        ExampleMatcher matcher = ExampleMatcher.matching()
//                .withIgnoreCase("name");
//
//        //.withIgnoreCase("name")                                                 .withIgnoreCase("name")
//        //.withIgnoreNullValues();                                                  where name 出错  如果为空的话要使用.withIgnoreNullValues();
//        //category对象 {id:12,name:"果汁"} -> where id = 12 and name = "果汁"
//
//
//        Optional<Category> category = categoryRepository.findOne(
//                Example.of(Category.builder().name(name).build(), matcher));
//
//        if (category.isPresent()){
////            return category.get();
////        }else {
////            return null;
////        }
//    }

    public Category findOne(String name) {
        Optional<Category> category = categoryRepository.findCategoryByNameLike(name);

        if (category.isPresent()){
            return category.get();
        }else {
            return null;
        }
    }

    public Category update(Long id,String newName){
        Optional<Category> oldCategory = categoryRepository.findById(id);
        if (oldCategory.isPresent()){
            Category category = oldCategory.get();
            category.setName(newName);
            return categoryRepository.saveAndFlush(category);
        }else{
            return null;
        }

    }

}